package com.devshephard.juchm.reentrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

public class ReentrantLockTimeOutDemo {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 启动...");
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {  //trylock方法支持载入两个参数,支持超时等待
                    // 超过指定时间获取不到锁将会返回
                    System.out.println(Thread.currentThread().getName() + " 获取等待 1s 后失败，返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                System.out.println(Thread.currentThread().getName() + " 获得了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");
        lock.lock();
        System.out.println(Thread.currentThread().getName() + " 获得了锁");
        t1.start();
        try {
            TimeUnit.SECONDS.sleep(4);
        } finally {
            lock.unlock();
        }
    }

}
